package com.example.luckybag

import android.accessibilityservice.AccessibilityService
import android.app.Notification
import android.app.PendingIntent
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import com.example.luckybag.service.LuckyBagService
import com.example.luckybag.service.LuckyServiceProvide
import com.example.luckybag.utils.Utils

/**
 * 文件名： <br/>
 * 描述：无障碍抢红包逻辑 核心服务🌝🌝🌝
 *
 * @author wulinran
 * @since 2023/2/10 10:19
 */
class AccessibilityBusiness {

    fun dealEvent(
        event: AccessibilityEvent,
        service: AccessibilityService,
        viewGet: LuckyBagService.ViewGet
    ) {
        if(!Utils.luckyPackageSwitch()){
            return
        }
        when (event.eventType) {
            //  实话谁说  部分版本可能不会有这个通知  直接用NotificationListenerService替换吧
            AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> handleNotification(event)
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {
                val className = event.className.toString()
                val packageName = event.packageName.toString()
                Log.e("测试无障碍", className)

                // 拿到对应处理的服务类，内部通过packageName过滤
                val luckyBagService = LuckyServiceProvide.getService(packageName, service)
                luckyBagService?.dealClassName(className,viewGet)
            }
        }
    }

    /**
     * 处理通知栏信息
     *
     * 如果是红包的提示信息,则模拟点击
     *
     * @param event
     */
    private fun handleNotification(event: AccessibilityEvent) {
        val texts = event.text
        if (texts.isNotEmpty()) {
            for (text in texts) {
                val content = text.toString()
                //如果微信红包的提示信息,则模拟点击进入相应的聊天窗口
                if (content.contains("[微信红包]") || content.contains("[红包]")) {
                    if (event.parcelableData != null && event.parcelableData is Notification) {
                        val notification: Notification? = event.parcelableData as Notification?
                        val pendingIntent: PendingIntent = notification!!.contentIntent
                        try {
                            pendingIntent.send()
                        } catch (e: PendingIntent.CanceledException) {
                            e.printStackTrace()
                        }
                    }
                }
            }
        }

    }


}